<template>
  <div class="employees">
    <el-card class="top">
      <div class="top-main">
        <div class="left">
          <span class="left-txt">
            <i class="el-icon-info" />
            共{{ total }}条数据
          </span>
        </div>
        <el-button type="primary" @click="addEvent">新增用户</el-button>
        <el-button type="danger" @click="outExcel">简单表头导出</el-button>
        <el-button type="info">复杂表头导出</el-button>
        <el-button
          type="success"
          @click="$router.push('/employees/import')"
        >excel导入</el-button>
      </div>
    </el-card>
    <el-card>
      <el-table :data="list">
        <el-table-column label="序号" type="index" width="50">
          <template v-slot="{ $index }">
            <div>
              {{ (page.page - 1) * page.size + $index + 1 }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="username" label="姓名" sortable />
        <el-table-column prop="staffPhoto" label="头像" width="60">
          <template v-slot="{ row }">
            <img
              v-errorimg
              class="avatar"
              :src="row.staffPhoto"
              alt=""
              @click="showCode(row.staffPhoto)"
            >
          </template>
        </el-table-column>
        <el-table-column prop="mobile" label="手机号" sortable />
        <el-table-column prop="workNumber" label="工号" sortable />
        <el-table-column
          prop="formOfEmployment"
          label="聘用形式"
          sortable
          :formatter="formatterEmployment"
        />
        <el-table-column prop="departmentName" label="部门" sortable />
        <el-table-column
          prop="timeOfEntry"
          label="入职时间"
          sortable
          :formatter="formatterTime"
        />
        <el-table-column
          prop="enableState"
          label="账户状态"
          sortable
          :formatter="formatterState"
        />
        <el-table-column label="操作" width="300px">
          <template v-slot="{ row }">
            <div>
              <el-button
                type="text"
                @click="$router.push('/employees/detail/' + row.id)"
              >查看</el-button>
              <el-button
                v-if="isShowBtn('employees_zzbtn')"
                type="text"
              >转正</el-button>
              <el-button type="text">调岗</el-button>
              <el-button type="text">离职</el-button>
              <el-button type="text" @click="roleEvent(row)">角色</el-button>
              <el-button type="text" @click="delEvent(row.id)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="page">
        <el-pagination
          :current-page.sync="page.page"
          :page-sizes="[1, 5, 10, 30, 100, 200, 300, 400]"
          :page-size.sync="page.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 新增弹框组件 -->
    <Add ref="add" @getData="getData" />
    <!-- 员工头像二维码 -->
    <imgCode ref="code" />
    <SetRole ref="role" />
  </div>
</template>

<script>
import { sysUser, sysUserDelete } from '@/api/employees'
import employeesData from '@/api/constant/employees'
import Add from './components/Add.vue'
import moment from 'moment'
import { export_json_to_excel } from '@/vendor/Export2Excel.js'
import imgCode from './components/imgCode.vue'
import SetRole from './components/SetRole.vue'

export default {
  components: {
    Add,
    imgCode,
    SetRole
  },
  data() {
    return {
      list: [],
      page: {
        page: 1,
        size: +localStorage.getItem('employees_pagesize') || 10
      },
      total: 100
    }
  },
  created() {
    this.getData()
  },
  methods: {
    async getData() {
      const res = await sysUser(this.page)
      this.list = res.data.rows
      this.total = res.data.total
    },
    // 页容量改变，持久化保证更好的用户体验，数字转化成字符串
    handleSizeChange() {
      localStorage.setItem('employees_pagesize', this.page.size + '')
      this.getData()
    },
    // 页码改变
    handleCurrentChange() {
      this.getData()
    },
    // 聘用形式枚举格式转换
    formatterEmployment(row, column, cellValue, index) {
      const findItem = employeesData.hireType.find(
        (item) => +item.id === +cellValue
      )
      return findItem ? findItem.value : '-'
    },
    // 账户状态枚举格式转换
    formatterState(row, column, cellValue, index) {
      const findItem = employeesData.stausInfos.find(
        (item) => +item.id === +cellValue
      )
      return findItem ? findItem.value : '-'
    },
    // 时间格式化
    formatterTime(row, column, cellValue, index) {
      return moment(cellValue).format('YYYY-MM-DD')
    },
    // 新增用户
    addEvent() {
      this.$refs.add.show = true
    },
    // 删除用户
    async delEvent(id) {
      await this.$confirm('您确定删除该项吗？', '温馨提示')
      await sysUserDelete(id)
      this.$message.success('删除成功')
      if (this.page.page > 1 && this.list.length === 1) {
        this.page.page--
      }
      this.getData()
    },
    async outExcel() {
      // 获取全部员工数据
      const res = await sysUser({
        page: 1,
        size: 9999999999
      })
      // 数据转换
      const header = [
        '序号',
        '姓名',
        '头像',
        '手机号',
        '工号',
        '聘用形式',
        '部门',
        '入职时间',
        '账户状态'
      ]
      const data = res.data.rows.map((item, index) => {
        return [
          index + 1,
          item.username,
          item.staffPhoto,
          item.mobile,
          item.workNumber,
          item.formOfEmployment,
          item.departmentName,
          item.timeOfEntry,
          item.enableState
        ]
      })
      // 调用导出excel方法
      export_json_to_excel({
        header: header,
        data: data,
        filename: '员工列表'
      })
    },
    // 显示员工头像二维码
    showCode(imgSrc) {
      this.$refs.code.show = true
      this.$nextTick(() => {
        this.$refs.code.toCode(imgSrc)
      })
    },
    // 角色按钮点击事件
    roleEvent(row) {
      this.$refs.role.show = true
      this.$refs.role.getRoleList()
      this.$refs.role.getUserRole(row.id)
    }
  }
}
</script>

<style lang="scss" scoped>
.employees {
  padding: 20px;
  .top {
    margin-bottom: 20px;
    .top-main {
      display: flex;
      align-items: center;
      .left {
        flex: 1;
        .left-txt {
          padding: 10px;
          background-color: #e6f7ff;
          border: 1px solid #a5ddff;
          border-radius: 8px;
          i {
            color: #409eff;
          }
        }
      }
    }
  }
  .avatar {
    width: 30px;
    height: 30px;
    object-fit: contain;
  }
  .page {
    text-align: center;
    padding-top: 20px;
  }
}
</style>
